package com.chujian.framework.starter.feign.config;

import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSON;
import com.chujian.framework.auth.AccessorHolder;
import com.chujian.framework.auth.SecurityConst;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;

/**
 * @author ：yj
 * @date ：2020-08-13
 * OpenFeign 调用时携带登录用户信息
 */
@ConditionalOnClass(RequestInterceptor.class)
@Slf4j
public class FeignAccessorRequestInterceptor implements RequestInterceptor, InitializingBean {

    // 需要向下传递的 Header
    private Set<String> requestHeaders = new HashSet<>();

    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            Enumeration<String> headerNames = request.getHeaderNames();
            if (headerNames != null) {
                String headerName;
                String headerValue;
                while (headerNames.hasMoreElements()) {
                    headerName = headerNames.nextElement();
                    if (requestHeaders.contains(headerName)) {
                        headerValue = request.getHeader(headerName);
                        requestTemplate.header(headerName, headerValue);
                    }
                }
            }
        }

        // 访问者信息，再写一下
        if (null != AccessorHolder.getAccessor()) {
            requestTemplate.header(SecurityConst.ACCESSOR_HEADER, Base64.encode(JSON.toJSONString(AccessorHolder.getAccessor())));
        }
    }

    @Override
    public void afterPropertiesSet() {
        requestHeaders.add(SecurityConst.TOKEN_HEADER); // token向下传递
        requestHeaders.add(SecurityConst.TOKEN_INNER_MARK_HEADER); // 内部调用Token

        requestHeaders.add(SecurityConst.ACCESSOR_HEADER); // 访问者信息
        requestHeaders.add(SecurityConst.REAL_REQUEST_URL_HEADER); // 原始请求地址

    }
}
